package com.dgut.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dgut.admin.param.NoticeAddParam;
import com.dgut.admin.param.NoticeModifyParam;
import com.dgut.admin.service.NoticeService;
import com.dgut.common.entity.Notice;
import com.dgut.common.enums.StatusEnum;
import com.dgut.common.mapper.NoticeMapper;
import com.dgut.common.utils.ApiException;
import com.dgut.common.utils.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author zyq
 * @Date 2022/4/8 11:41
 * @Description TODO
 * @Version 1.0
 **/
@Service
@Slf4j
public class NoticeServiceImpl implements NoticeService {
    private final NoticeMapper noticeMapper;
    public NoticeServiceImpl(NoticeMapper noticeMapper) {
        this.noticeMapper = noticeMapper;
    }

    @Override
    public void addNotice(NoticeAddParam param) {
        noticeMapper.insert(new Notice()
                .setTitle(param.getTitle())
                .setContent(param.getContent())
                .setState(param.getState())
                .setUrl(param.getUrl())
                .setPublishTime(StatusEnum.ACTIVE.getState().equals(param.getState()) ? new Date() : null));
    }

    @Override
    public PageVO listNotice(Integer pageNum, Integer pageSize, Integer state) {
        IPage<Notice> page = new Page<Notice>().setCurrent(pageNum).setSize(pageSize);
        QueryWrapper<Notice> wrapper = new QueryWrapper<>();
        if (state != null) {
            wrapper.eq("state", state);
        }
        IPage<Notice> noticeIPage = noticeMapper.selectPage(page, wrapper);
        return PageVO.convert(noticeIPage);
    }

    @Override
    @Transactional
    public void modifyNotice(NoticeModifyParam param) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(param, notice);
        notice.setPublishTime(StatusEnum.ACTIVE.getState().equals(param.getState()) ? new Date() : null);
        int result = noticeMapper.updateById(notice);
        if (result != 1) {
            throw new ApiException("【NoticeServiceImpl - modifyNotice】fail to modify.");
        }
    }

    @Override
    @Transactional
    public void deletedNotice(Integer id) {
        int result = noticeMapper.deleteById(id);
        if (result != 1) {
            throw new ApiException("【NoticeServiceImpl - deletedNotice】fail to delete.");
        }
    }


}
